// JavaScript Document
//获取图片宽度
  function setElementHeight($elements, ratio) {
          if (typeof $elements === 'object') {
              if (typeof ratio === 'object' ||
                  typeof ratio === 'string' ||
                  !isFinite(ratio) ||
                  ratio < 1/8 ||
                  ratio > 8) {
                  ratio = 1;
              }
              for (var i = 0; i < $elements.length; i++) {
                  console.log($elements[i].clientWidth);
                  $elements[i].style.height = $elements[i].clientWidth * ratio + 'px';
              }
          }
  }
  var addCookie=function(objName,objValue,objHours){
      var str = objName + "=" + escape(objValue)+'; path=/; domain='+window.$config.hostname;
      if(objHours > 0){
          var date = new Date();
          var ms = objHours*3600*1000;
          date.setTime(date.getTime() + ms);
          str += "; expires=" + date.toGMTString();
      }
      document.cookie = str;
  }
  var getCookie=function(objName){
      var arrStr = document.cookie.split("; ");
      for(var i = 0;i < arrStr.length;i ++){
          var temp = arrStr[i].split("=");
          if(temp[0] == objName) return unescape(temp[1]);
      }
  }


  //获取携带参数值
  function getQueryString(name){//如：http://www.baidu.com/?tab=2  →  getQueryString('tab') →   2;
    var href=document.location.href;
    var string=href.substring(href.indexOf('?')+1);
    var oArr={};
    var arr=string.split('&');
    for(var i=0;i<arr.length;i++){
      var newArr=arr[i].split('=');
      oArr[newArr[0]]=newArr[1];
    };
    return oArr[name]?decodeURIComponent(oArr[name]):'';
  };

  //设置参数信息
  function setQuery(name,value){  //如：http://www.baidu.com/?tab=2  →  setQuery('tab','') →   http://www.baidu.com/  → setQuery('tab','222') →   http://www.baidu.com/?tab=222 →  setQuery({'tab':'','a':'1','b':'2'}) →   http://www.baidu.com/?a=1&b=2 ;
    var href=document.location.href;
    var strging='';
    var len=arguments.length;
    var oArr={};
    if(href.indexOf('?')!==-1){
      var string=href.substring(href.indexOf('?')+1);
      var arr=string.split('&');
      for(var i=0;i<arr.length;i++){
        var newArr=arr[i].split('=');
        oArr[newArr[0]]=encodeURIComponent(newArr[1]);
      }
    };
    if(len===1){
      for(var i in name){
        if(name[i]===''){
          delete oArr[i];
        }else{
          oArr[i]=encodeURIComponent(name[i]);
        };      
      };
    }else if(len==2){
      if(value===''){
        delete oArr[name];
      }else{
        oArr[name]=encodeURIComponent(value);
      };  
    };
    var aStrging=[];
    for(var i in oArr){
      var a=(i+'='+oArr[i]);
      aStrging.push(a);
    };  
    if(aStrging.length){
      var newQuery=aStrging.join('&');
      document.location.href=href.substring(0,href.indexOf('?'))+'?'+newQuery;
    }else{
        document.location.href=href.substring(0,href.indexOf('?'));
    };
  };
  //获取cookie
  function newgetCookie(name){
          var result=""
          var bcookie;
          //对cookie信息进行相应的处理，方便搜索
          var myCookie = ""+document.cookie+";";
          var searchName =""+name+"=";
          var satrtOfCookie = myCookie.indexOf(searchName);
          var endOfCookie;
          if(satrtOfCookie != -1){
              satrtOfCookie += searchName.length;
              endOfCookie = myCookie.indexOf(";",satrtOfCookie);
              result = (myCookie.substring(satrtOfCookie,endOfCookie));
          }
         bcookie=result.split("%7E")[1]
          return bcookie;
       } //end function
    //  接口参数
  var getargument="key=1c31da331a88d869214ce47d18a74973&timestamp=1430961343&resign=07654d13a014d9e58b9ec2e3cbeaf90e";
  /***************登录注册表单验证*******************/
$(function(){
      $('.u-form #phone').on('blur',function(){
          if(this.value==""){
            error("请输入手机号码"); 
          }else if(this.value!==""&&!/(^(13|14|15|17|18|19)\d{9}$)/.test(this.value)){
              error("请输入正确的手机号码"); 
          }
      });
      $('.u-form #password').on('blur',function(){
          if(this.value==""){
            error("请输入密码"); 
          }else if(this.value!=""&&!/^(\w){6,12}$/.test(this.value)){
               error("请输入正确的密码格式"); 
          }
      });
      //跳转绑定微信
      function getweixin(val,nick_name){
        $.ajax({
          url:window.$config.mybuy+"/userabout/Mine/bindOpenId",
          type:"get",
          dataType:"jsonp",
          jsonp: "jsonpcallback",//服务端用于接收callback调用的function名的参数
          jsonpCallback:"jsonpcallback",//callback的function名称
          data:{"user_id":val,"nick_name":nick_name},
          async:false,
          success:function(msg){
          }
        })
      }
    
  //发送验证码
      $('#getCode,#fogetCode').on('click',function(){
          var InterValObj;
          var count=60;
          var curCount;
              curCount=count;
          var phone=$('#phone').val();
              if(phone!=""&&/(^(13|14|15|17|18)\d{9}$)/.test(phone)){
                  var getCodeurl;
                  if($(this).attr('id')=="getCode"){
                      getCodeurl="../../userabout/User/sendCode"
                  }else if($(this).attr('id')=="fogetCode"){
                      getCodeurl="../../userabout/User/userforgetPwdsendCode"
                  }
                   $.ajax({
                       url:getCodeurl, //目标地址
                       type: "post", //用POST方式传输
                       dataType: "json", //数据格式:JSON
                       data:  {"phone":phone,"key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e"},
                       error: function (XMLHttpRequest, textStatus, errorThrown) { },
                       success: function (msg){
                          $('.get-code').attr("disabled","true");
                          $('.get-code').addClass("actcolor");
                          $('.get-code').val(curCount+"秒以后重新获取");
                          InterValObj=setInterval(SetRemainTime,1000);
                        }
                  });
              }else{
                  error("请输入正确的手机号码");
              }
              function SetRemainTime(){
                  if(curCount==1){
                      clearInterval(InterValObj);
                      $('.get-code').removeAttr('disabled');
                      $('.get-code').removeClass("actcolor");
                      $('.get-code').val("重新获取");
                  }
                  else{
                      curCount--;
                      $('.get-code').val(curCount+"秒以后重新获取");
                  }
              }

      });
        var $phone=$('#phone');
        var $password=$('.password');
          //注册
      $('#sign').on('click',function(){
         var phone=$('#phone').val();
          var Captcha=$("#verifycode").val();
          var PassWord=$('#password').val();
          var channel;
          if($phone.val()==""){
               error("请输入手机号码");
               return false;
          }else if($phone.val()!==""&&!/(^(13|14|15|17|18)\d{9}$)/.test($phone.val())){
              error("请输入正确的手机号码");
               return false;
          }
          if(Captcha==""){
              error("请输入正确的验证码");
               return false;
          }
          if($password.val()==""){
             error("请输入密码");
              return false;
          }else if($password.val()!=""&&!/^(\w){6,12}$/.test($password.val())){
              error("请输入正确的密码格式");
               return false;
          }
          var referrerUserId=0;
          var sceneid=0;
          var signdata;
          if (getQueryString("shareid") || getQueryString("sceneid")) {
             referrerUserId=getQueryString("shareid")?getQueryString("shareid"):0;
             sceneid=newgetCookie("sceneId")?newgetCookie("sceneId"):0;
             signdata={"phone":phone,"captcha":Captcha,"password":PassWord,channel:"30","key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e","registerplatform":"3000","referrerUserId":referrerUserId,"sceneid":sceneid}
          }else{
             signdata={"phone":phone,"captcha":Captcha,"password":PassWord,channel:"30","key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e","registerplatform":"3000"}
          }
           $.ajax({
               url: 'register.html', //目标地址
               type: "post", //用POST方式传输
               dataType: "json", //数据格式:JSON
               data:signdata,
               error: function (XMLHttpRequest, textStatus, errorThrown) { },
               success: function (msg){
                     if(msg.status==200){
                        error("注册成功");
                        setTimeout(geturl,1000);
                        getweixin(msg.stdclass.list.userId,msg.stdclass.list.nickName)
                      }else{
                         error(msg.stdclass.list);
                      }
                }
            });
           function geturl(){
              if(referrerUserId!=0){
               location.href='download.html';
              }else{
                location.href='login.html';
              } 
           }
      });
      //登陆
      $('#login').on('click',function(){
         var phone=$('#phone').val();
         var Pass=$('#password').val();
          if($phone.val()==""){
              error("请输入手机号码");
              return false;
          }else if($phone.val()!==""&&!/(^(13|14|15|17|18)\d{9}$)/.test($phone.val())){
              error("请输入正确的手机号码");
               return false;
          }       
          if($password.val()==""){
              error("请输入密码");
               return false;
          }
         $.ajax({
               url: '../../userabout/User/login', //目标地址
               type: "post", //用POST方式传输
               dataType: "json", //数据格式:JSON
               data:{"loginname":phone,"password":Pass,"key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e","platfrom":1},
               error: function (XMLHttpRequest, textStatus, errorThrown) { },
               success: function (msg){      
                  if(msg.status==200){
                    error("登陆成功");
                    addCookie("userIdval",msg.stdclass.list.userId);
                    getweixin(msg.stdclass.list.userId,msg.stdclass.list.nickName)
                  //return false;  
                  var fe="@-%^%*";
                    var param=phone+fe+Pass+fe+"1c31da331a88d869214ce47d18a74973"+fe+"1430961343"+fe+"07654d13a014d9e58b9ec2e3cbeaf90e"+fe+1;
                    if(getQueryString("to_url")){  
                      location.href=getQueryString("to_url")+'&param='+param;
                     }else{
                       location.href=$(".gourl").val()+'?param='+param;;
                     }
                  }else{
                       error(msg.stdclass.list);
                  }
                }
            });
      });
  //找回密码
      $('#step-btn').on('click',function(){
          var phone=$('#phone').val();
          var Captcha=$("#verifycode").val();
          if($phone.val()==""){
            error("请输入手机号码");
             return false;
          }else if($phone.val()!==""&&!/(^(13|14|15|17|18)\d{9}$)/.test($phone.val())){
              error("请输入正确的手机号码");
              return false;
            }
          if(Captcha==""){
               error("请输入正确的验证码");
                return false;
          }
           $.ajax({
                 url: '../../userabout/User/checkNextforgetCode', //目标地址
                 type: "post", //用POST方式传输
                 dataType: "json", //数据格式:JSON
                 data:  {"phone":phone,"code":Captcha,"key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e"},
                 error: function (XMLHttpRequest, textStatus, errorThrown) { },
                 success: function (msg){
                         if(msg.status==200){
                            addCookie("phoneval",phone);
                            location.href='setpwd';
                    }else{
                         error(msg.stdclass.list);
                    }
                  }
            });
      });
     //重置密码
      $('#newpass').on('click',function(){
          var Pass=$('#password').val();
          if($password.val()==""){
            error("请输入密码");
            return false;
          }else if($password.val()!=""&&!/^(\w){6,12}$/.test($password.val())){
              error("请输入正确的密码格式");
              return false;
          }
          phone=getCookie("phoneval");
           $.ajax({
                   url: '../../userabout/User/resetPwd', //目标地址
                   type: "post", //用POST方式传输
                   dataType: "json", //数据格式:JSON
                   data:  {"phone":phone,"password":Pass,"key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e"},
                   error: function (XMLHttpRequest, textStatus, errorThrown) { },
                   success: function (msg){
                      if(msg.status==200){
                          error("密码修改成功");
                          location.href='login';
                      }else{
                         error(msg.stdclass.list);
                      }  
                    }
                  });
      });
      $('#passbtn').toggle(function(){
          $('#passbtn').addClass('pass-show');
          $('#password').prop("type","text");
      },function(){
          $('#passbtn').removeClass('pass-show');
          $('#password').prop("type","password");

      });
      //修改密码
      $("#updatepwd").click(function(){
          if($("#oldpassword").val()==""){
              error("请输入原密码");
              return false ;
          }else if($("#password").val()==""){
              error("请输入新密码");
              return false ;
          }else if($("#newpassword").val()==""){
              error("请再一次输入新密码");
              return false ;
          }
          if($("#password").val()!=$("#newpassword").val()){
              error("两次密码输入不一致");
              return false ;
          }
          var flag=true;
          $(".password").each(function(){
              if($(this).val()!=""&&!/^(\w){6,12}$/.test($(this).val())){
              flag=false;            
             }
          })
          if(flag==false){
             error("请输入正确的密码格式");
            return false;
          }
          var UserId=newgetCookie("currentUserId");
          var OldPwd=$("#oldpassword").val();
          var NewPwd=$("#password").val();
           $.ajax({
                   url: '../../apiadapter/Index/userCenter', //目标地址
                   type: "post", //用POST方式传输
                   dataType: "json", //数据格式:JSON
                   data:  {"user_id":UserId,"oldpwd":OldPwd,"newpwd":NewPwd,"url":"userabout/User/updatePwd","key":"1c31da331a88d869214ce47d18a74973","timestamp":"1430961343","resign":"07654d13a014d9e58b9ec2e3cbeaf90e"},
                   success: function (msg){
                      if(msg.status==200){
                          error("密码修改成功");
                          location.href='/userabout/Webindex/logout';
                      }else{
                         error(msg.stdclass.list);
                      }  
                    },
                  error: function (XMLHttpRequest, textStatus, errorThrown) { }
            });
          
      })

    /*返回*/
    $(".J_backToPrev").click(function(){
        window.history.go(-1)
    })
    /*马上支付*/
    $(".immediate_pay").click(function(){
         var backurl="http://10.43.50.3:89/Payment/PayComplete?flag=1";
         var user_id=$("#user_id").val();
         var order_id=$("#order_id").val();
            $.ajax({
                 url:"../../../customized/webindex/payurl",
                 type:"post",
                 data:{"user_id":user_id,"order_id":order_id,"backurl":backurl},
                 success:function(msg){
                   location.href=msg; 
                 },
                 error:function(){

                 }
            })

    })
});
    /*回到顶部*/
    //首先将#back-to-top隐藏
    $("#ScrollToTop").hide();
    //当滚动条的位置处于距顶部100像素以下时，跳转链接出现，否则消失
    $(function() {
      $(window).scroll(function() {
          if ($(window).scrollTop() > 200) {
              $("#ScrollToTop").fadeIn(1500);
          } else {
              $("#ScrollToTop").fadeOut(1500);
          }
      });
      //当点击跳转链接后，回到页面顶部位置
      $("#ScrollToTop").click(function() {
          $('body,html').animate({
              scrollTop: 0
          },
          1000);
          return false;
      });
    });
    /*清除提示框*/
    function  clearerror(){
     $('body').find('.onError').fadeOut(500);
    }
    function error(errorval){
    if($(".onError").length>0){
      $(".onError").show().text(errorval)
    }else{
      $('body').append('<div class="onError">'+errorval+'</div>');
    }
    setTimeout(clearerror,800);
    }
    

//让div在屏幕上下左右居中
   $.fn.center = function(){
   	this.css(
   		{"position":"absolute",
   		  "left":($(window).width()-this.width())/2+"px",
   		  "top":($(window).height()-this.height())/2+"px"
   		})
     return this;
   }
